#include "rtc.h"

time_t rtc_get_seconds(void)
{
	volatile mml_rtc_regs_t	*reg_rtc = (volatile mml_rtc_regs_t*) MML_RTC_IOBASE;
	
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);
	return (time_t) (reg_rtc->sec);
}

static void rtc_reset(void)
{
	volatile mml_rtc_regs_t *reg_rtc = (volatile mml_rtc_regs_t*) MML_RTC_IOBASE;
	
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);
	reg_rtc->cr = 0x8000;
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);
	reg_rtc->sec = 0x00000000;
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);
	reg_rtc->cr = 0x8000;
	
	return;
}

/*
	@para
		reset: 0--> not reset rtc regs
		reset: 1--> reset rtc regs
		sec:  init rtc time
*/
u8 rtc_init(time_t sec,  u8 reset)
{
	SYSP_ST *sysp;	
	volatile mml_rtc_regs_t	*reg_rtc = (volatile mml_rtc_regs_t*) MML_RTC_IOBASE;

	sysp = sys_para_get();

	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);

	if ((reg_rtc->cr >> MML_RTC_CR_RTCE_OFST) & MML_RTC_CR_RTCE_MASK){
		sysp->startup = TRUE;
		if(reset){
			rtc_reset();
		}
		else{
			return 1;
		}
	}else{
		sysp->startup = FALSE;
	}
		
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);

	reg_rtc->sec = sec;
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);

	reg_rtc->ssec = 0;
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);

	reg_rtc->cr = MML_RTC_CR_WE_MASK << MML_RTC_CR_WE_OFST; 
	while ((reg_rtc->cr >> MML_RTC_CR_BUSY_OFST) & MML_RTC_CR_BUSY_MASK);

	reg_rtc->cr = (MML_RTC_CR_WE_MASK << MML_RTC_CR_WE_OFST) | (MML_RTC_CR_X32KMD_QUIET << MML_RTC_CR_X32KMD_OFST) | (MML_RTC_CR_RTCE_MASK << MML_RTC_CR_RTCE_OFST); // 0x8801

	return 0;
}



